package com.qf.service.impl;

import com.qf.constant.CacheConstants;
import com.qf.feign.CacheFeign;
import com.qf.model.StandardSubmit;
import com.qf.service.FilterChainManager;
import com.qf.service.FilterChainService;
import com.qf.util.PushMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * 责任链管理者
 *
 * @author lixu
 */
@Service
@Slf4j
public class FilterChainManagerImpl implements FilterChainManager {

    /**
     * 获取SpringIOC容器中  6个实现类同时实现一个接口
     */
    @Autowired
    private Map<String, FilterChainService> filterChainServiceMap;//现在是6个长度

    @Autowired
    private CacheFeign cacheFeign;
    @Autowired
    private PushMsgUtil pushMsgUtil;

    /**
     * 下面这个方法就是责任链执行方法
     *
     *  log.info("[策略模块 - 策略管理员] 无策略可以执行!!!submit = {}", standardSubmit);
     *
     * @param submit
     */
    @Override
    public void executeFilter(StandardSubmit submit) {

        //   "phase,black,limitFiveMinutes,dirtyWords,fee,router"
//        1. 调用cache模块获取redis中过滤器的执行顺序
        String cacheKey = CacheConstants.CACHE_PREFIX_CLIENT + submit.getClientID();
        String filters = cacheFeign.hget(cacheKey, "filters");
        if (StringUtils.isEmpty(filters)) {
            log.info("[策略模块 - 策略管理员]--当前用户没有策略:[" + submit.getClientID() + "]!!!");
            return;
        }
//        例如 : "black,router,fee,phase,limit,dirtyWord"
//        2. 根据逗号分割, 获取过滤器执行顺序数组
        String[] fs = filters.split(",");
//        3. 遍历过滤器执行顺序数组
        for (String f : fs) {

//        4. 获取执行的过滤器实现类对象, FilterChainService chain = filterMap.get("black")
            FilterChainService filterChainService = filterChainServiceMap.get(f);
            if(filterChainService == null){
                continue;
            }
//        5. 执行具体策略业务方法, chain.strategy(StandardSubmit submit);
            boolean isSuccess = filterChainService.strategy(submit);
//        6. 判断执行结果, 如果返回为false停止执行, 返回为true继续执行
            if(!isSuccess){
                //false 不成功
                log.info("[策略模块 - 策略管理员]--当前用户:[" + submit.getClientID() + "]:不符合" + f + "策略!!!");
                //发送日志
                pushMsgUtil.sendLog(submit, f);
                //发送报告
                pushMsgUtil.pushReport(submit,f);
                return;
            }
        }

    }
}
